
const baseURL = 'https://gitee.com/api/v5/repos/gitlyl/family_blog/contents';
// https://gitee.com/api/v5/repos/gitlyl/family_blog/contents/blog?ref=gh-pages&access_token=b03f89ca80a684fb34dde249e8f5eebd
// https://gitee.com/api/v5/repos/gitlyl/family_blog/contents/

/**
 *  使用Promise 对wx.request进行分装
 * @param {*} params 
 */

function request(params = { methods, url, data }) {
  return  new Promise(function (resolve,reject) {
    wx.request({
      url: baseURL + params.url,
      method: params.method,
      data: params.data ? JSON.stringify(params.data) : null,
      header: { 
        'Content-Type':'application/json; charset=utf-8',
       },
      timeout: 5000,
      success(res) { 
        // console.log(res.statusCode)
        if (res.statusCode >=200 && res.statusCode < 300 || res.statusCode == 304) {
          if (res.data.length != 0) {
            resolve(res.data);
          } else {
            wx.showToast({
              title: '暂无数据',
              content: res.data.msg,
              icon: 'error',
              duration: 2000,
              showCancel: false,
              success:function(res) {}
            })
            reject(res.data);
          }
        } else if(res.statusCode == 401) {
          wx.showToast({
            title: '登录过期！',
            content: 'Token过期请重新登录',
            showCancel: false,
            success: function(res) {
              refresh_Token()
            }
          })
          reject(res);
        } else {
          wx.showToast({
            title: '网络错误！',
            content: '网络请求超时！',
            showCancel: false,
            success: function(res) {}
          })
          reject(res);
        } 
      },
      fail (err) {
        reject(err)
      },
      complete(){
        wx.hideLoading({})  //关闭请求提示框
      }
    })
  })
}


function refresh_Token() {
  console.log("刷新token")
  wx.request({
    url: 'https://gitee.com/oauth/token?grant_type=refresh_token&refresh_token=' + wx.getStorageSync('refresh_token'),
    method:'POST',
    success:function(res){
      console.log(res.data.access_token)
      wx.setStorageSync('access_token', res.data.access_token)
      wx.setStorageSync('refresh_token', res.data.refresh_token)
      wx.setStorageSync('created_at', res.data.created_at)
      wx.setStorageSync('token_type', res.data.token_type)
    },
    fail:function(res){},
    complete: function(res) {},
  })
}

module.exports = {
  request: request
}
